#!/bin/bash

RED='\033[0;31m'
GREEN='\033[0;32m'
NC='\033[0m' # No Color

# 检查参数
if [ $# -eq 0 ]; then
    echo -e "${RED}错误：请指定地区代码参数，例如：./auto_download_convert.sh cn${NC}"
    exit 1
fi

ZONE=$1
DATE=$(date +"%Y%m%d")
FILENAME="zones/${ZONE}_${DATE}.zone"
IPSET_NAME="${ZONE}_ips"

# 下载文件函数
download_file() {
    declare -A CITY2URL=(
        ["cn"]="https://metowolf.github.io/iplist/data/country/CN.txt"
        ["bj"]="https://metowolf.github.io/iplist/data/cncity/110000.txt"
        ["sh"]="https://metowolf.github.io/iplist/data/cncity/310000.txt"
        
    )
    
    URL=${CITY2URL[$ZONE]}
    if [ -z "$URL" ]; then
        echo -e "${RED}错误：不支持的地区代码${NC}"
        exit 1
    fi

    echo "正在下载 $URL..."
    if wget -q "$URL" -O "$FILENAME"; then
        echo -e "${GREEN}文件下载成功: $FILENAME${NC}"
    else
        echo -e "${RED}文件下载失败${NC}"
        exit 1
    fi
}

# 转换为ipset格式函数
convert_to_ipset_format() {
    echo "开始转换文件为ipset格式..."
    IPSET_FILE="zones/${IPSET_NAME}.ipset"
    
    echo "create ${IPSET_NAME} hash:net" > "$IPSET_FILE"
    
    TOTAL_LINES=$(wc -l < "$FILENAME")
    CURRENT=0
    
    while IFS= read -r line; do
        ((CURRENT++))
        printf "\r转换进度: %d/%d" $CURRENT $TOTAL_LINES
        echo "add ${IPSET_NAME} $line" >> "$IPSET_FILE"
    done < "$FILENAME"
    
    echo -e "\nadd ${IPSET_NAME} 192.168.0.0/24" >> "$IPSET_FILE"
    echo "add ${IPSET_NAME} 192.168.1.0/24" >> "$IPSET_FILE"
    
    echo -e "\n${GREEN}转换完成: $IPSET_FILE${NC}"
}

# 主流程
download_file
convert_to_ipset_format

exit 0